from apiview.views import View
from django.http import HttpResponse
import requests
from PIL import Image
from io import BytesIO

class MaImage(View):
    def get(self,request):
        # 高德地图API接口地址
        geocode_url = "https://restapi.amap.com/v3/geocode/geo"
        staticmap_url = "https://restapi.amap.com/v3/staticmap"

        # 高德地图API密钥
        key = "ea86e187d8c6152f19f48ac218eabf4e"

        # 获取用户输入的省市区地址
        province = request.GET.get('province')
        city = request.GET.get('city')
        district = request.GET.get('district')
        address = province + city + district

        # 发送GET请求获取地址的经纬度坐标
        geocode_params = {
            "key": key,
            "address": address,
        }
        geocode_response = requests.get(geocode_url, params=geocode_params)
        geocode_data = geocode_response.json()

        # 解析经纬度坐标
        location = geocode_data["geocodes"][0]["location"]

        # 发送GET请求获取地图图像
        staticmap_params = {
            "key": key,
            "location": location,
            "zoom": 10,
            "size": "800*600",
        }
        staticmap_response = requests.get(staticmap_url, params=staticmap_params)
        staticmap_data = staticmap_response.content

        # 将返回的内容转换为图像对象
        image_obj = Image.open(BytesIO(staticmap_data))

        image_obj.show()


        # 将图像对象转换为字节流
        image_stream = BytesIO()
        image_obj.save(image_stream, format='PNG')
        image_stream.seek(0)

        # 创建HttpResponse对象，设置content_type为image/png
        response = HttpResponse(content_type='image/png')
        response.write(image_stream.read())

        return response
